#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

const static int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(const std::string &ip, uint16_t port):
    _sockfd(defaultfd),
    _port(port),
    _ip(ip)
    {

    }

    void InitServer()
    {
        // 1. 创建udp socket 套接字 --- 必须要做的
        int _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket errror %s, %d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);

        // 2.0 填充sockaddr_in结构
        struct sockaddr_in local; // struct sockaddr_in 系统提供的数据类型。local是变量，用户栈上开辟空间。int a = 100; a = 20;
        bzero(&local, sizeof(local));//对local 内存空间清空
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); // port要经过网络传输给对面，先到网络，_port：主机序列-> 主机序列，转成网络序列
        // a. 字符串风格的点分十进制的IP地址转成 4 字节IP
        // b. 主机序列，转成网络序列
        // in_addr_t inet_addr(const char *cp) -> 同时完成 a & b
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // "192.168.3.1" -> 字符串风格的点分十进制的IP地址 -> 4字节IP


        //local.sin_addr.s_addr = INADDR_ANY; // 接受来自任何网络接口的连接时，会使用 INADDR_ANY 进行绑定。

        // 2.1 bind sockfd和网络信息(IP(?) + Port)
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0) 
        {
            LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "socket bind success\n");
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            sleep(1);
            LOG(DEBUG, "server is running...\n");
        }
        _isrunning = false;

    }

    ~UdpServer()
    {

    }

private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;
    bool _isrunning;
};